package org.example.course.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.example.commonapi.domain.Course;
import org.example.commonapi.domain.CourseClass;
import org.example.commonapi.domain.R;
import org.example.commonapi.domain.StudentClass;
import org.example.commonapi.dto.LoginInfo;
import org.example.commonapi.dto.StudentDto;
import org.example.commonapi.util.JwtUtil;
import org.example.course.service.CourseClassService;
import org.example.course.service.CourseService;
import org.example.course.service.StudentClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/course")
@Slf4j
public class StudentClassController {

    @Resource
    private StudentClassService studentClassService;
    @Resource
    private CourseClassService courseClassService;
    @Resource
    private JwtUtil jwtUtil;

    /**
     *  查看班级学生（老师,学生）
     * @return
     */
    @GetMapping("/list/studentclass/{classId}")
    public R listStudentClass(@PathVariable("classId") Long classId,String username,String no) {
        List<StudentDto> list=studentClassService.listStudent(classId,username,no);
        return R.success(list);
    }



    /**
     * 老师邀请学生(邀请多人可以)
     * @param studentClass
     * @return
     */
    @PostMapping("/invite/studentclass")
    public R inviteStudent(@RequestBody List<StudentClass> studentClass) {
//        判断学生是否已经加入班级
        R result=isJoin(studentClass);
        if(result!=null)return result;
//        邀请学生至班级
        studentClassService.inviteStudent(studentClass);
        return R.success();
    }

    /**
     * 修改学生班级（老师，学生）
     * @return
     */
    @PutMapping("/update/studentclass")
    public R updateStudentClass(@RequestBody StudentClass studentClass) {
        studentClassService.updateStudentClass(studentClass);
        return R.success();
    }


    /**
     * 把这个学生从这个班级踢掉，或者学生自己退出（学生，老师）
     * @param studentId
     * @param classId
     * @return
     */
    @DeleteMapping("/delete/studentclass/{studentId}/{classId}")
    public R deleteStudentClass(@PathVariable("studentId") Long studentId,@PathVariable("classId") Long classId) {
        LambdaQueryWrapper<StudentClass> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentClass::getStudentId,studentId).eq(StudentClass::getClassId,classId);
        studentClassService.remove(queryWrapper);
        LambdaQueryWrapper<CourseClass> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(CourseClass::getId,classId);
        CourseClass courseClass=courseClassService.getOne(queryWrapper1);
        courseClass.setNumber(courseClass.getNumber()-1);
        courseClassService.updateById(courseClass);
        return R.success();
    }


//    @PostMapping("/jion/studentclass")
//    public R joinStudentClass(@RequestParam String invite,@RequestBody StudentClass studentClass) {
//        if(StringUtils.isEmpty(invite))return R.error("邀请码不能为空");
//        if(studentClassService.joinStudentClass(invite,studentClass)){
//            R result=isJoin(studentClass);
//            if(result!=null)return result;
//            studentClassService.save(studentClass);
//            LambdaQueryWrapper<CourseClass> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(CourseClass::getId,studentClass.getClassId());
//            CourseClass courseClass=courseClassService.getOne(queryWrapper);
//            courseClass.setNumber(courseClass.getNumber()+1);
//            courseClassService.save(courseClass);
//            return R.success();
//        }
//        else return R.error("邀请码错误，请重新输入");
//    }

    /**
     * 学生加入班级（学生）
     * @param invite
     * @param request
     * @return
     */
    @PostMapping("/join/studentclass")
    public R joinStudentClass(@RequestParam String invite, HttpServletRequest request) {
        log.info("invite:{}",invite);
        if(StringUtils.isEmpty(invite))return R.error("邀请码不能为空");
        LoginInfo loginInfo=jwtUtil.parseJwt(request.getHeader("token"));
        LambdaQueryWrapper<CourseClass> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseClass::getInvite,invite);
        CourseClass courseClass=courseClassService.getOne(queryWrapper);
        if(courseClass==null)return R.error("邀请码错误，请重新输入");
        else{
            R result = isJoin(courseClass, loginInfo.getId());
            if (result != null) return result;
            StudentClass studentClass=new StudentClass(loginInfo.getId(), courseClass.getId());
            studentClassService.joinStudentClass(invite, studentClass);
            studentClassService.save(studentClass);
            courseClass.setNumber(courseClass.getNumber() + 1);
            courseClassService.updateById(courseClass);
        }
        return R.success(courseClass.getCourseId());
    }



    /**
     * 判断学生是否已经加入班级
     * @param
     * @return
     */
    public R isJoin(CourseClass courseClass,Long userId){
        LambdaQueryWrapper<StudentClass> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentClass::getStudentId,userId).eq(StudentClass::getClassId,courseClass.getId());
        if(studentClassService.exists(queryWrapper))return R.error("学生已加入班级");
        else return null;
    }

    /**
     * 判断学生是否已经加入班级
     * @param studentClasses
     * @return
     */
    public R isJoin(List<StudentClass> studentClasses){
        for(StudentClass studentClass:studentClasses){
            LambdaQueryWrapper<StudentClass> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StudentClass::getStudentId,studentClass.getStudentId()).eq(StudentClass::getClassId,studentClass.getClassId());
            if(studentClassService.exists(queryWrapper))return R.error("有学生已加入班级");
        }
        return null;
    }
}
